<template>
  <!-- 当点击 取消按钮 时，关闭弹窗 -->
  <el-dialog
    :title="$t('mesCapacityCodeReprint.reprint')"
    :visible.sync="visible"
    width="70%"
    top="4vh"
    :append-to-body="true"
    @close="clearDialog()"
    v-loading="loding"
    :close-on-click-modal="false"
  >
    <div>
      <ele-form
        v-model="createData"
        v-bind="formConfig"
        ref="form"
        v-loading="loading"
      ></ele-form>

      <ele-page
        v-if="isShow"
        :otherParams="otherParams"
        :formConfig="searchConfig"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="mesProdCapacitycodeReprint"
      ></ele-page>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="clearDialog()">{{ $t("common.cancel") }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getDict } from "@/api/common";
import { printTemplateInfoName } from "@/api/barcodeprint/mesBarcodeprintHistory";

import {
  mesProdBarcodeReprint,
  mesProdBarcodeReprintList,
  selectMesProdBarcodeReprintDetail,
} from "@/api/print/mesProdBarcodePrint";

import {
  checkCapacityCode, //校验是否已经生成对应类型容量码
  templateType, //获取生码分类
  getProdByOrder, //根据订单获取型号
  selectCommonProduceRelByProduce, //根据型号、分类获取生码规则接口
  getCapacityCodeList, //获取容量/数量列表接口,
  mesProdCapacitycodeReprint, //补打审核列表查询
  reprintCapacitySel, //补打查询获取已打印容量码数据
  reprintCapacitySelList, //补打查询获取需补打的条码信息
  reprintCapacityDel, //补打审核删除
} from "@/api/print/mesCapacityCode";

const repairRowConfig = [
  {
    name: $i18n.t("common.delete"),
    type: "danger",
    class: "row-btn-primary",
    handleName: "delete",
    show: (row) => {
      return row.status === "noExamine";
    },
  },
  {
    name: $i18n.t("common.print"),
    type: "primary",
    class: "row-btn-primary",
    handleName: "print",
    show: (row) => {
      return row.status === "examinePass" && row.isPrint === "0";
    },
  },
];

export default {
  name: "repairPrintTable",
  data() {
    let that = this;
    return {
      otherParams: {
        orderCode: "",
        prodCode: "",
        prodOrderType: "",
      },
      loding: false,
      loading: false,
      visible: false,
      isShow: false,
      mesProdCapacitycodeReprint,
      operateList: [
        {
          name: $i18n.t("common.add"),
          type: "primary",
          icon: "el-icon-circle-plus-outline",
          handleName: "add", //点击时返回的标识
        },
      ],
      searchConfig: {
        inline: true,
        formDesc: {
          status: {
            layout: 7,
            type: "select",
            label: $i18n.t("common.status"),
            prop: {
              value: "value",
              text: "description",
            },
            options: async (data) => {
              let res = await getDict("mes_barcode_reprint_status");
              console.log("mes_barcode_reprint_status", res);
              return res.data.result || [];
            },
          },
        },
      },
      createData: {
        orderCode: null,
        goodsCode: null,
        printSort: null,
        productType: null,
      },
      printCount: [],
      formConfig: {
        span: 24,
        isShowBackBtn: false,
        isShowSubmitBtn: false,
        labelPosition: "right",
        formDesc: {
          orderCode: {
            //生产工单编码
            type: "input",
            label: $i18n.t("mesCapacityCodePrintingRecord.orderCode2"),
            layout: 8,
            disabled: true,
          },
          printSort: {
            type: "select",
            label: $i18n.t("mesCapacityCodePrintingRecord.printSort"),
            layout: 8,
            prop: {
              value: "value",
              text: "description",
            },
            options: async (data) => {
              const params = {};
              const list = await templateType(params);
              return list.data.result;
            },
            on: {
              change(val) {
                that.createData.printSort = val;
                (that.formConfig.formDesc.goodsCode.options = async (data) => {
                  const params = {
                    orderCode: data.orderCode,
                  };
                  const list = await getProdByOrder(params);
                  that.goodsCodeList = list.data.result;
                  return list.data.result;
                }),
                  that.changeCode();
              },
            },
            disabled: false,
          },
          goodsCode: {
            //型号
            type: "select",
            label: $i18n.t("mesCapacityCodePrintingRecord.goodsCode"),
            layout: 8,
            prop: {
              value: "prodCode",
              text: "prodName",
            },
            options: async (data) => {
              const params = {
                orderCode: data.orderCode,
              };
              const list = await getProdByOrder(params);
              that.goodsCodeList = list.data.result;
              return list.data.result;
            },
            slots: {
              default(h, options) {
                let data = that.goodsCodeList;
                if (data && data.length > 0) {
                  return data.map((option) =>
                    h("el-option", { attrs: { value: option.prodCode } }, [
                      h("span", { style: { float: "left" } }, option.prodName),
                      h(
                        "span",
                        {
                          style: {
                            float: "right",
                            color: "#8492a6",
                            fontSize: "13px",
                          },
                        },
                        option.prodCode
                      ),
                    ])
                  );
                } else {
                  return [];
                }
              },
            },
            on: {
              change(val) {
                that.createData.goodsCode = val;
                let goodsCodeList = that.goodsCodeList;
                let goodsCode = goodsCodeList.find((item) => {
                  return item.prodCode == val;
                });
                if (goodsCode) {
                  that.createData.productType = goodsCode.productType;
                }

                that.changeCode();
              },
            },
            disabled: false,
            displayFormatter: (data) => {
              if (!data) return "";
              return that.goodsCodeList.find((item) => item.prodCode === data)
                .prodName;
            },
          },
        },
      },
      column: [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          width: 60,
          fixed: "left",
        },
        {
          label: $i18n.t("mesCapacityCodePrintingRecord.codeStrategy"),
          prop: "orderCode",
          width: 150,
        },
        {
          label: $i18n.t('mesCapacityCodePrintingRecord.printSort'),
          prop: "capacityType",
          width: 150,
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            let res = await getDict("template_type_capacitycode");
            return res.data.result || [];
          },
        },
        {
          label: $i18n.t('mesCapacityCodePrintingRecord.goodsCode'),
          prop: "prodCode",
          width: 150,
        },
        {
          label: $i18n.t('mesCapacityCodePrintingRecord.startBarCode'), //"补打起始唯一码",
          prop: "startBarcode",
          width: 320,
          showOverflowTooltip: true,
        },
        {
          label: $i18n.t("mesCapacityCodePrintingRecord.endBarcode"),
          prop: "endBarcode",
          width: 320,
          showOverflowTooltip: true,
        },
        {
          label: $i18n.t("mesCapacityCodePrintingRecord.printTemp"), //"打印模板",
          prop: "printTemp",
        },
        {
          label: $i18n.t("mesCapacityCodePrintingRecord.createByName"), //"申请人",
          prop: "createByName",
        },
        {
          label: $i18n.t("mesCapacityCodePrintingRecord.createTime"), // "申请时间",11
          prop: "createTime",
          width: 180,
        },
        {
          label: $i18n.t("common.status"), //"状态",
          prop: "status",
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            let res = await getDict("mes_barcode_reprint_status");
            return res.data.result || [];
          },
        },
        {
          label: $i18n.t("mesCapacityCodePrintingRecord.examineByName"), // "审核人",
          prop: "examineByName",
        },
        {
          label: $i18n.t("mesCapacityCodePrintingRecord.examineTime"), // "审核时间",
          prop: "examineTime",
          width: 180,
        },
        {
          label: $i18n.t("mesCapacityCodePrintingRecord.examineContent"), // "审核内容",
          prop: "examineContent",
        },
        {
          label: $i18n.t("mesCapacityCodePrintingRecord.isPrint"), //"是否打印",
          prop: "isPrint",
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            let res = await getDict("yes_or_not");
            return res.data.result || [];
          },
        },
        {
          prop: "operate",
          label: $i18n.t("common.operation"),
          width: 160,
          fixed: "right",
          showOverflowTooltip: false,
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={repairRowConfig}
                onRowOperate={this.repairRowOperate}
              ></ele-row-operation>
            );
          },
        },
      ],
      tableData: [],
      params: {},
    };
  },
  methods: {
    //初始化
    init(params) {
      this.params = params;
      this.otherParams = {
        isPrint: 0,
        capacityType: "",
        prodCode: "",
        orderCode: params.orderCode,
      };
      this.createData = {
        orderCode: params.orderCode,
        goodsCode: null,
        printSort: null,
        productType: null,
      };
      this.visible = true;
      if (this.$refs.eleTable) {
        this.refresh();
      }
    },
    refresh() {
      this.$nextTick(() => {
        this.$refs.eleTable.refresh();
      });
    },

    clearDialog() {
      this.isShow = false;
      this.visible = false;
      this.$emit("refreshList");
    },

    // 表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name;
      const fnc = {
        add: () => {
          this.$parent.$refs.repairPrintModel.init({
            ...this.params,
            ...this.createData,
            printCount: "",
            printCountList: this.printCount,
            quantity: 0,
            type: 1, //需要审批
          });
        },
      };
      fnc[data.handleName]();
    },
    // 补打申请表格行操作事件
    repairRowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        delete: () => {
          reprintCapacityDel(row.id).then((res) => {
            this.$message.success($i18n.t("common.deleteSuccess"));
            this.refresh();
          });
        },
        print: async () => {
          let {
            id,
            orderCode,
            prodCode,
            capacityType,
            startBarcode,
            endBarcode,
          } = row;
          const params = {
            masterId: id,
            orderCode: orderCode,
            prodCode: prodCode,
            capacityType: capacityType,
            startBarCode: startBarcode,
            endBarCode: endBarcode,
          };

          let data = await reprintCapacitySelList(params);
          let obj = {
            masterId: id,
            barcodePrintTempCode: row.printTempCode,
            printType: 1,
            barcodePrintTemp: row.printTemp,
            barCodeResult: data.data.result,
          };

          localStorage.splitPrint = JSON.stringify(obj);
          this.visible = false;
          this.refresh(false);
          this.$router.push("/splitPrint");
        },
      };
      fnc[handleName] && fnc[handleName]();
    },
    // 类型型号选择处理
    changeCode() {
      let createData = this.createData;
      let check = {
        orderCode: createData.orderCode,
        prodCode: createData.goodsCode,
        productType: createData.productType,
        capacityType: createData.printSort,
      };
      //当分类和型号都存在时获取效验容量码是否生成
      if (check.capacityType && check.prodCode) {
        this.loading = true;
        checkCapacityCode(check).then((res) => {
          this.loading = false;
          if (res.data.result) {
            getCapacityCodeList(check).then((res) => {
              if (res.data.success) {
                let tableData = res.data.result.barCodeResult;
                let printCount = [];
                tableData.forEach((item) => {
                  item.amount =
                    parseInt(item.sumCodeNum) - parseInt(item.hasPrintNum);
                  item.oldAmount =
                    parseInt(item.sumCodeNum) - parseInt(item.hasPrintNum);
                  if (item.hasPrintNum > 0) {
                    printCount.push({ count: item.count });
                  }
                });
                this.printCount = printCount;
                let otherParams = {
                  orderCode: createData.orderCode,
                  prodCode: createData.goodsCode,
                  capacityType: createData.printSort,
                };

                this.getCitycodeReprint(otherParams);
              } else {
                this.capacityTableForm = [];
                this.isShow = false;
              }
            });
          } else {
            this.capacityTableForm = [];
            this.isShow = false;
          }
        });
      }
    },
    async getCitycodeReprint(otherParams) {
      this.otherParams = {
        prodCode: otherParams.prodCode,
        capacityType: otherParams.capacityType,
        orderCode: otherParams.orderCode,
      };
      let res = await mesProdCapacitycodeReprint();
      if (res.data.success) {
        console.log(res.data);
        this.isShow = true;
      }
    },
    // 点击打印按钮
    handleRequest() {},
  },
};
</script>
